﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Starksoft.Cryptography.OpenPGP;
using AKMII.DMRA.DataAccess;
using AKMII.DMRA.Business.Rule;

namespace AKMII.DMRA.DataLoader
{
    public class Decryptor
    {
        private bool Decrypt(string file, string destPath, string fileName)
        {
            FileStream sourceFile = null;
            FileStream outputFile = null;

            try
            {
                if (!string.IsNullOrEmpty(file))
                {
                    GnuPG gnu = new GnuPG();

                    int index = fileName.IndexOf(".pgp", StringComparison.CurrentCultureIgnoreCase);
                    gnu.Passphrase = SystemConfiguration.CommonSetting.PrivateKeyPassword;
                    sourceFile = new FileStream(file, FileMode.Open);
                    outputFile = new FileStream(destPath + fileName.Remove(index), FileMode.Create);

                    gnu.Decrypt(sourceFile, outputFile);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occurs in decrypt process", ex);
                return false;
            }
            finally
            {
                if (sourceFile != null)
                {
                    sourceFile.Close();
                }
                if (outputFile != null)
                {
                    outputFile.Close();
                }
            }

            return true;
        }

        public void Process(string source, string destination)
        {
            if (!string.IsNullOrEmpty(source) && !string.IsNullOrEmpty(destination))
            {
                if (source.EndsWith(@"\") && destination.EndsWith(@"\"))
                {
                    DirectoryInfo di = new DirectoryInfo(source);
                    FileInfo[] fi = di.GetFiles("*.pgp");

                    CommandHistoryAccessor accessor = new CommandHistoryAccessor();
                    DateTime dateTime = accessor.GetLastExecuteTime(Command.Decrypt.ToString());

                    foreach (FileInfo file in fi)
                    {
                        if (file.LastWriteTime > dateTime)
                        {
                            if (Decrypt(Path.Combine(source, file.Name), destination, file.Name))
                            {
                                accessor.UpdateLastExecuteTime(Command.Decrypt.ToString(), DateTime.Now);
                            }
                        }
                    }
                }
            }
        }
    }
}
